<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" :v-if="showDeploy"  @click="handleDeploy(['frontend', 'backend'])">重新部署</a-button>
        <a-button type="primary" @click="openSourceApp"> 配置数据源 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="createActions(record)"
          />
        </template>
      </template>
    </BasicTable>
    <ReadmeDrawer @register="registerReadmeDrawer" />
    <SourceAppDrawer @register="registerSourceAppDrawer" />
    <DeployModal @register="registerDeployModal" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '@/components/Table';

  import { useMessage } from '@/hooks/web/useMessage';
  import { useRequest } from '@vben/hooks';
  import { getPluginList, installPlugin, uninstallPlugin, getPluginSourceApp } from '@/api/plugin';
  import { InstallPluginParams, UninstallPluginParams } from '@/api/model/plugin';
  import { useDrawer } from '@/components/Drawer';
  import ReadmeDrawer from './ReadmeDrawer.vue';
  import SourceAppDrawer from './SourceAppDrawer.vue';
  import { columns, searchFormSchema } from './data';
  import { pluginStateEnum } from '@/enums/plugin';
  import { getDeployRequest } from '@/api/deploy';
  import DeployModal from './DeployModal.vue';
  import { deploy, DeployParams } from '@/api/deploy';
  import { useModal } from '@/components/Modal';

  const [registerDeployModal, { openModal: openDeployModal }] = useModal();

  const { createMessage } = useMessage();
  const { success } = createMessage;

  const [registerReadmeDrawer, { openDrawer: openReadmeDrawer }] = useDrawer();
  const [registerSourceAppDrawer, { openDrawer: openSourceAppDrawer }] = useDrawer();

  const sourceApp = ref(null);
  const showDeploy = ref(false);

  const { data: deployRequestResposne, run, cancel } = useRequest(getDeployRequest, {
    pollingInterval: 3000,
    onFinally: handleDeployRequest,
  });

  function handleDeployRequest() {
    if (deployRequestResposne.value.pending > 0) {
      cancel();
      showDeploy.value = true;
      if (deployRequestResposne.value.unread > 0) {
        openDeployModal();
      }
    }
  }

  onMounted(async () => {
    const res = await getPluginSourceApp();
    sourceApp.value = res.source_app;
    if (sourceApp.value === "") {
      openSourceApp();
    }
    run();
  });

  const [registerTable, { reload }] = useTable({
    title: '扩展列表',
    api: getPluginList,
    columns,
    formConfig: {
      labelWidth: 60,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: true,
    actionColumn: {
      width: 200,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
    },
  });

  const createActions = (record) => {
    const actions: ActionItem[] = [
      {
        label: 'README',
        onClick: () => {
          openReadme(record)
        },
      },
      {
        label: '源码',
        onClick: () => {
          openGitUrl(record)
        },
      },
    ];
    if (record.state === pluginStateEnum.INSTALL_FAILED || record.state === pluginStateEnum.NOT_INSTALL) {
      actions.push(
        {
          label: '安装',
          onClick: () => {
            handleInstall(record)
          },
        },
      )
    }
    if (record.state === pluginStateEnum.UNINSTALL_FAILED) {
      actions.push(
        {
          label: '卸载',
          onClick: () => {
            handleUninstall(record)
          },
        },
      )
    }
    return actions;
  };

  async function handleInstall(record: Recordable) {
    const params: InstallPluginParams = {
      key: record.key,
      name: record.name,
      git_url: record.git_url,
    }
    await installPlugin(params);
    success('请求成功，等待后台安装')
    reload();
  }

  async function handleUninstall(record: Recordable) {
    const params: UninstallPluginParams = {
      key: record.key,
    }
    await uninstallPlugin(params);
    success('请求成功，等待后台卸载')
    reload();
  }

  function openReadme(record: Recordable) {
    openReadmeDrawer(true, {
      record,
    });
  }

  function openGitUrl(record: Recordable) {
    const newWindow = window.open(record.git_url, '_blank');
    if (newWindow !== null) {
      newWindow?.focus();
    }
  }

  function openSourceApp() {
    openSourceAppDrawer(true, {
      sourceApp,
    });
  }

  async function handleDeploy(endpoints: string[]) {
      const params: DeployParams = {
        endpoints: endpoints,
      }
      await deploy(params);
      success('正在重启，可能需要几分钟')
    }

</script>